/*
 * BanBu_SnowFall
 * @description 本文件提供个人空间动态插件的方法
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供个人空间动态插件的方法
 */

#import "BanBu_SnowFall.h"
#import "UIImageView+WebCache.h"
@implementation BanBu_SnowFall


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // set the background color to something COLD
        self.backgroundColor = [UIColor clearColor];
        
        // load our flake image we will use the same image over and over
        flakeImage = nil;
        
        [self startFull];
        // start a timet that will fire 20 times per second
    }
    return self;
}
- (void)startFull
{
    [self onTimer];
    if(!_timer)
    {
        _timer = [NSTimer scheduledTimerWithTimeInterval:(1.6) target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
    else
    {
        [_timer fire];
    }
    self.userInteractionEnabled = NO;
}
- (void)endFull
{
    if(_timer)
    {
        [_timer invalidate];
        _timer = nil;
    }
}

/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect
 {
 // Drawing code
 }
 */
// Timer event is called whenever the timer fires
- (void)onTimer
{
	// build a view from our flake image
	UIImageView* flakeView = [[UIImageView alloc] initWithImage:flakeImage];
    if(_flakeImageURL)
    {
        [flakeView setImageWithURL:[NSURL URLWithString:_flakeImageURL] placeholderImage:flakeImage andType:0];
    }
    else
    {
        return;
    }
	// use the random() function to randomize up our flake attributes
	int startX = round(random() % 320);
	int endX = round(random() % 320);
	double scale = 2 / round(random() % 100) + 1.0;
	double speed = 2 / round(random() % 100) + 1.0;

    //之前设置是下面这句，起始位置y是根据25.0 * scale计算的，但是程序运行一会就会闪退，未找到原因
    //flakeView.frame = CGRectMake(startX, -25.0 * scale, 25.0 * scale, 25.0 * scale);]
//    NSLog(@"scale:::%f",scale);
    NSString * infStr = [NSString stringWithFormat:@"%f",scale];
    
    //获取的随机scale有时会出现inf的现象，造成flakeView.frame不是一个有效地数据，闪退
    if ([infStr isEqualToString:@"inf"])
    {
        return;
    }
	flakeView.frame = CGRectMake(startX, -(25.0 * scale), 25.0 * scale, 25.0 * scale);

    // put the flake in our main view
	[self addSubview:flakeView];
    [flakeView release];
    CABasicAnimation* rotationAnimation;
    rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    rotationAnimation.toValue = [NSNumber numberWithFloat: M_PI * 2.0 ];
    
    
    rotationAnimation.duration = 10.0;
    rotationAnimation.RepeatCount = FLT_MAX;
    rotationAnimation.cumulative = NO;
    [flakeView.layer addAnimation:rotationAnimation forKey:nil];
    __block UIImageView * bflakeView = flakeView;
    
    [UIView animateWithDuration:10 *speed animations:^{
         bflakeView.frame = CGRectMake(endX, __MainScreen_Height + 25.0 * scale, 25.0 * scale, 25.0 * scale);
        bflakeView.alpha = 0.3;
    } completion:^(BOOL finished) {
//        [beslf onAnimationComplete:nil finished:nil context:bflakeView];
        if (finished)
        {
            [bflakeView removeFromSuperview];
            bflakeView = nil;
        }
    }];
    
    //原来的方法，不能再动态过程中改变透明度
//	[UIView beginAnimations:nil context:flakeView];
//	// set up how fast the flake will fall
//	[UIView setAnimationDuration:20 * speed];
//	
//	// set the postion where flake will move to
//	flakeView.frame = CGRectMake(endX, __MainScreen_Height + 25.0 * scale, 25.0 * scale, 25.0 * scale);
//	NSLog(@"flakeView222:%d %f %f %f",endX,__MainScreen_Height + 25.0 * scale, 25.0 * scale, 25.0 * scale);
//	// set a stop callback so we can cleanup the flake when it reaches the
//	// end of its animation
//	[UIView setAnimationDidStopSelector:@selector(onAnimationComplete:finished:context:)];
//	[UIView setAnimationDelegate:self];
//	[UIView commitAnimations];
}
- (void)onAnimationComplete:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context {
	
	UIImageView *flakeView = context;
	[flakeView removeFromSuperview];
	// open the debug log and you will see that all flakes have a retain count
	// of 1 at this point so we know the release below will keep our memory
	// usage in check
	[flakeView release];
	
	
}
- (void)dealloc {
    if(_timer)
    {
        [_timer invalidate],_timer = nil;
    }
    
	[flakeImage release];
	[super dealloc];
}
@end
